package com.hctforgreen.greenservice;

import java.util.ArrayList;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.ctr.DbController;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.model.BookListEntity;
import com.hctforgreen.greenservice.model.CheckVersionEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.utils.FileCacheUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LanguageSettingUtil;
import com.hctforgreen.greenservice.utils.LoginInStoreUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.ThemeStoreUtil;
import com.hctforgreen.greenservice.utils.VersionDialogUtil;
import com.hctforgreen.greenservice.utils.VersionUtil;
import com.hctforgreen.greenservice.utils.WifiFreshStateStoreUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * 软件设置页
 * 
 * @author Tallen Zhai
 * 
 */
public class SettingActivity extends ParentActivity {

	private final static int THEME_SETTING_REQUEST_CODE = 13;
	private final static int DOWNLOAD_STORE_POSITION = 0x12;
	private SwitchLanguageReceiver mLanguageReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);

		initTitleButtonBar();
		initSkinLayout();
		initWindow();
		initSwitchLanguageReciever();
	}


	private void initTitleButtonBar() {
		final TextView titleTv = (TextView) findViewById(R.id.tv_title);
		titleTv.setText(getString(R.string.setting_title_hint));

		final ImageButton backBtn = (ImageButton) findViewById(R.id.btn_back);
		backBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	private void updateCacheSize(final String local) {
		final TextView clearCacheTv = (TextView) findViewById(R.id.tv_clear_cache);
		final View loadingView = findViewById(R.id.pb_loading_clear_cashe);
		loadingView.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				ArrayList<String> excludeFilePathList = getExcludeFilePathList();
				FileCacheUtil cacheUtil = new FileCacheUtil();

				final String fileDirectoryLength = cacheUtil
						.getFileDirectoryLength(SettingActivity.this, local,
								excludeFilePathList);

				runOnUiThread(new Runnable() {
					public void run() {
						loadingView.setVisibility(View.GONE);
						clearCacheTv.setText(fileDirectoryLength);
					}
				});
			};
		}.start();

	}

	/**
	 * 获取要排除的文件列表 耗时需优化
	 * 
	 * @return 文件路径列表
	 */
	private ArrayList<String> getExcludeFilePathList() {
		long time = System.currentTimeMillis();
		DbController dbController = new DbController(SettingActivity.this);
		BookListEntity listEntity = dbController
				.getBookListEntityUseSerieId("",0);
		System.out.println(System.currentTimeMillis() - time);
		ArrayList<String> excludeFilePathList = new ArrayList<String>();
		// if (listEntity != null && listEntity.dataList != null) {
		// for (BookEntity book : listEntity.dataList) {
		// if (book.bookZipState
		// .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_ING)
		// || book.bookZipState
		// .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_ANALISIS_ING)
		// || book.bookZipState
		// .equals(HctConstants.ON_ACTIVITY_KEY_BOOK_ZIP_STATE_DOWNLOAD_WAITING))
		// {
		// String zipPath = BookEntity.makeBookFileName(
		// book.download_url, book.suffix,
		// getApplicationContext());// 压缩包|源文件 路径
		// excludeFilePathList.add(zipPath);
		// }
		// String dePath = BookEntity.makeBookFileName(book.download_url,
		// book.suffix, getApplicationContext()).replace(
		// book.suffix, "");// 解压后的文件路径
		// excludeFilePathList.add(dePath);
		// }
		// }
		System.out.println(System.currentTimeMillis() - time);
		return excludeFilePathList;
	}

	/**
	 * 清除缓存确认对话框
	 */
	private void clearCacheDiaolg(final FrameLayout parentLyt,
			final String fileDirectoryPath) {
		Dialog dialog = null;
		AlertDialog.Builder builder = new AlertDialog.Builder(
				SettingActivity.this);
		builder.setTitle(R.string.dialog_default_title_hint)
				.setMessage(getString(R.string.you_make_sure_clear_cache_hint))
				.setNegativeButton(R.string.dialog_cancel_hint,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						})
				.setPositiveButton(R.string.dialog_confirm_hint,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								doDeleteCache(parentLyt, fileDirectoryPath);
								dialog.dismiss();
							}
						});
		dialog = builder.create();
		dialog.show();
	}

	private void doDeleteCache(final FrameLayout parentLyt,
			final String fileDirectoryPath) {
		MobclickAgent.onEvent(SettingActivity.this, "Account_clean_cache");
		final ProgressBar loadingPb = (ProgressBar) findViewById(R.id.pb_loading_clear_cashe);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				switch (msg.what) {
				default:
					parentLyt.setClickable(true);
					loadingPb.setVisibility(View.GONE);
					updateCacheSize(fileDirectoryPath);
					break;
				}
			}
		};
		parentLyt.setClickable(false);
		loadingPb.setVisibility(View.VISIBLE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					ArrayList<String> excludeFilePathList = getExcludeFilePathList();

					FileCacheUtil cacheUtil = new FileCacheUtil();
					cacheUtil.deleteFileDirectory(fileDirectoryPath,
							excludeFilePathList);
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void initWindow() {

		initThemeSettingLayout();
		initLanguageSetting();
		initAboutUsLayout();
		initQrcodeDownloadLayout();
		initSupportMidLayout();
		initAddFeedLayout();
		initUpgradeDescription();
		initVersionUpdateLayout();

		initClearCacheLayout();

		initLoginOutLayout();
		initDownLoadStoreLayout();
		initWifiFreshState();
		initPointsRule();

	}

	/**
	 * 语言设置
	 */
	private void initLanguageSetting() {

		final LinearLayout langaugeSetting = (LinearLayout) findViewById(R.id.lyt_language_setting);
		final TextView tvlanguage = (TextView) findViewById(R.id.tv_language);

		int lset = LanguageSettingUtil.get(getApplicationContext());
		switch (lset) {
		case -1:
			Locale locale = getResources().getConfiguration().locale;
			String language = locale.getLanguage();
			Log.w("locale.getLanguage()", language);
			if (language.endsWith("zh")) {
				tvlanguage.setText("中文版");
			} else if (language.endsWith("en")) {
				tvlanguage.setText("English");
			}
			break;

		case 0:
			tvlanguage.setText("中文版");
			break;
		case 1:
			tvlanguage.setText("English");
			break;
		}

		langaugeSetting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				startActivity(new Intent(SettingActivity.this,
						LanguageSettingActivity.class));
			}
		});

	}

	private void initPointsRule() {

		/**
		 * 积分规则
		 */
		final LinearLayout supportMidLyt = (LinearLayout) findViewById(R.id.lyt_points_rule);
		supportMidLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SettingActivity.this,
						SupportMidActivity.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_INFO_TYPE,
						SupportMidActivity.POINT_RULE);
				startActivity(intent);
			}
		});

	}

	private void initWifiFreshState() {
		final CheckBox tbWifi = (CheckBox) findViewById(R.id.tb_wifi_fresh);
		if (WifiFreshStateStoreUtil.get(getApplicationContext())) {
			tbWifi.setChecked(true);
		} else {
			tbWifi.setChecked(false);
		}

		tbWifi.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				if (isChecked) {
					WifiFreshStateStoreUtil.save(getApplicationContext(), true);
				} else {
					WifiFreshStateStoreUtil
							.save(getApplicationContext(), false);
				}
			}
		});
	}

	private void initDownLoadStoreLayout() {
		final TextView tvPath = (TextView) findViewById(R.id.tv_current_storage);
		tvPath.setText(getString(R.string.download_store_current)
				+ HctConstants.getBooksRootPath(getApplicationContext())
				+ HctConstants.BOOKS_CACHE_STORE_PATH);
		tvPath.setVisibility(View.GONE);
		findViewById(R.id.lyt_download_setting).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View v) {// 下载文件路径设置
						Intent intent = new Intent(getApplicationContext(),
								DownloadStoreSettingActivity.class);
						startActivityForResult(intent, DOWNLOAD_STORE_POSITION);
					}
				});

	}

	@Override
	protected void onResume() {

		super.onResume();
	}

	private void initClearCacheLayout() {
		/**
		 * 清除缓存
		 */
		final FrameLayout clearCacheLyt = (FrameLayout) findViewById(R.id.lyt_clear_cache);

		final String local = HctConstants
				.getBooksRootPath(getApplicationContext())
				+ HctConstants.BOOKS_CACHE_STORE_PATH;
		clearCacheLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				clearCacheDiaolg(clearCacheLyt, local);
			}
		});
		updateCacheSize(local);
	}

	private void initQrcodeDownloadLayout() {
		final LinearLayout qrcodeDownloadLyt = (LinearLayout) findViewById(R.id.lyt_qrcode_download);
		qrcodeDownloadLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SettingActivity.this,
						QrcodeDownloadActivity.class);
				startActivity(intent);
			}
		});
	}

	private void initAddFeedLayout() {
		/**
		 * 意见反馈
		 */
		final LinearLayout addFeedLyt = (LinearLayout) findViewById(R.id.lyt_add_feed);
		addFeedLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(SettingActivity.this,
						"Account_setting_feadback");

				Intent intent = new Intent(SettingActivity.this,
						AddFeedActivity.class);
				startActivity(intent);
			}
		});
	}

	private void initAboutUsLayout() {
		/**
		 * 关于我们
		 */
		final LinearLayout aboutUsLyt = (LinearLayout) findViewById(R.id.lyt_about_us);
		aboutUsLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(SettingActivity.this, "Account_about_us");
				Intent intent = new Intent(SettingActivity.this,
						AboutUsActivity.class);
				startActivity(intent);
			}
		});
	}

	private void initSupportMidLayout() {
		/**
		 * 支持机型
		 */
		final LinearLayout supportMidLyt = (LinearLayout) findViewById(R.id.lyt_support_mid);
		supportMidLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SettingActivity.this,
						SupportMidActivity.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_INFO_TYPE,
						SupportMidActivity.SUPPORT_MACHINE);
				startActivity(intent);
			}
		});
	}

	/**
	 * 版本更新说明
	 */
	private void initUpgradeDescription() {
		final LinearLayout supportMidLyt = (LinearLayout) findViewById(R.id.lyt_version_description);
		supportMidLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SettingActivity.this,
						SupportMidActivity.class);
				intent.putExtra(HctConstants.ON_ACTIVITY_KEY_INFO_TYPE,
						SupportMidActivity.VERSION_UPDATE);
				startActivity(intent);
			}
		});
	}
/**
 * 版本升级
 */
	private void initVersionUpdateLayout() {

		final TextView versionNameTv = (TextView) findViewById(R.id.tv_version_name);

		final String sVersionName = VersionUtil.getAppVersionName(this);
		versionNameTv.setText(sVersionName);

		final LinearLayout versionUpdateLyt = (LinearLayout) findViewById(R.id.lyt_version_update);
		versionUpdateLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(SettingActivity.this,
						"Account_version_update");

				versionNameTv
						.setText(getString(R.string.click_get_version_hint));
				loadVersionStatus(String.valueOf(sVersionName), true);
			}
		});
		loadVersionStatus(String.valueOf(sVersionName), false);
	}

	private void initThemeSettingLayout() {
		/**
		 * 主题设置
		 */
		final LinearLayout themeSettingLyt = (LinearLayout) findViewById(R.id.lyt_theme_setting);
		themeSettingLyt.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(SettingActivity.this,
						"Account_theme_setting");
				Intent intent = new Intent(SettingActivity.this,
						ThemeSettingActivity.class);
				startActivityForResult(intent, THEME_SETTING_REQUEST_CODE);
			}
		});
	}

	private void initLoginOutLayout() {
		final LinearLayout logOutView = (LinearLayout) findViewById(R.id.lyt_logout);
		LoginResultEntity entity = LoginResultStoreUtil.get(this);

		if (entity == null || entity.personId == null
				|| entity.personId.trim().equals("")) {
			logOutView.setVisibility(View.GONE);
		}
		logOutView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MobclickAgent.onEvent(SettingActivity.this,
						"Account_cancel_login");

				LoginResultEntity loginResultEntity = LoginResultStoreUtil
						.get(SettingActivity.this);
				LoginResultStoreUtil.delete(SettingActivity.this);
				LoginInStoreUtil.deleteAutoLoginIn(SettingActivity.this);
				Toast.makeText(SettingActivity.this,
						getString(R.string.logout_success), Toast.LENGTH_SHORT)
						.show();
				Intent intent = new Intent(SettingActivity.this,
						MainActivityV2.class);
				HctConstants.setFinish_mian_start_login(true);
				HctConstants.setLoginout_phone(loginResultEntity.phone);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
			}
		});
	}

	private void renderVersion(CheckVersionEntity entity,
			final boolean bShowDialog) {

		TextView versionNameTv = (TextView) findViewById(R.id.tv_version_name);
		final ImageView newIv = (ImageView) findViewById(R.id.iv_new);
		if (entity.isNew.equals("true")) {
			versionNameTv.setText(getString(R.string.is_new_version_hint));

			newIv.setVisibility(View.GONE);
			Toast.makeText(this, getString(R.string.is_new_version_hint),
					Toast.LENGTH_SHORT).show();
		} else if (entity.isNew.equals("false")) {
			versionNameTv.setText(getString(R.string.has_new_version_hint));
			newIv.setVisibility(View.VISIBLE);
			if (bShowDialog) {
				VersionDialogUtil versionDialogUtil = new VersionDialogUtil();
				versionDialogUtil.updateVersionRecommendDialog(
						SettingActivity.this, entity);
			}

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == DOWNLOAD_STORE_POSITION) {
			initDownLoadStoreLayout();
			initClearCacheLayout();
		}
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case THEME_SETTING_REQUEST_CODE:
				initSkinLayout();
				break;
			default:
				break;
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}
/**
 * 
 * @param versionCode--当前版本号
 * @param bShowDialog--是否弹出对话框
 */
	private void loadVersionStatus(final String versionCode,
			final boolean bShowDialog) {
		/**
		 * 版本升级
		 */
		final FrameLayout versionStatusLyt = (FrameLayout) findViewById(R.id.lyt_version_status);
		final ProgressBar loadingPb = (ProgressBar) versionStatusLyt
				.findViewById(R.id.pb_loading);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				loadingPb.setVisibility(View.GONE);
				versionStatusLyt.setClickable(true);
				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					hctResult = (HctResult) msg.obj;
					CheckVersionEntity entity = (CheckVersionEntity) hctResult.data;
					renderVersion(entity, bShowDialog);
					break;

				case HctConstants.STATUS_FAILD:
					Toast.makeText(SettingActivity.this,
							getString(R.string.net_error_hint),
							Toast.LENGTH_SHORT).show();
					break;
				}
			}

		};
		loadingPb.setVisibility(View.VISIBLE);
		versionStatusLyt.setClickable(false);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(
							SettingActivity.this);

					HctResult result = controller.checkVersion(versionCode);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	private void initSwitchLanguageReciever() {
		mLanguageReceiver = new SwitchLanguageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(MainActivityV2.SWITCH_LANGUAGE_ACTION_NAME);
		registerReceiver(mLanguageReceiver, filter);
	}

	public class SwitchLanguageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			finish();
		}
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(mLanguageReceiver);
		super.onDestroy();
	}
}
